package com.hsmpay.mobile.ds.impl;

import com.hsmpay.common.pojo.BasePojo;
import com.hsmpay.common.pojo.qian4.Qian4SendLog;
import com.hsmpay.common.util.NumberUtil;
import com.hsmpay.mobile.dao.terminal.TchannelDao;
import com.hsmpay.mobile.dao.terminal.TchannelMDao;
import com.hsmpay.mobile.dao.trans.TransOrderDao;
import com.hsmpay.mobile.ds.DS_RuiShengService;
import com.hsmpay.mobile.pojo.other.Settings;
import com.hsmpay.mobile.pojo.terminal.Tchannel;
import com.hsmpay.mobile.pojo.terminal.TchannelM;
import com.hsmpay.mobile.pojo.trans.TransOrder;
import com.hsmpay.mobile.service.other.SettingsService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import com.hsmpay.qian4.pojo.BalanceResult;
import com.hsmpay.qian4.pojo.PurchaseResult;
import com.hsmpay.qian4.pojo.RevocationResult;
import com.hsmpay.qian4.pojo.send.SendParam;
import com.hsmpay.yl8583.service.RuiShengPayService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 瑞升银联socket  服务接口 anxinybService
 *
 * @author 颜铃璋
 *         创建时间：2014-8-7
 */
@Service("ds_RuiShengService")
public class DS_RuiShengServiceImpl implements DS_RuiShengService<BasePojo, Long> {
    @Resource(name = "tchannelDao")
    TchannelDao<Tchannel, Long> tchannelDao;
    @Resource(name = "transOrderDao")
    private TransOrderDao<TransOrder, String> transOrderDao;//交易订单
    @Resource(name = "tchannelMDao")
    private TchannelMDao<TchannelM, String> tchannelMDao;//通道商户号表
    @Resource(name = "settingsService")
    private SettingsService<Settings,String> settingsService;//项目配置
    private Long flRoleId = 2l;
    private Long fdRoleId = 3l;
    private static int cnt = 0;
    private static int RuiSheng_TchannelId = 34;

    /**
     * 获取瑞升银联socket 接口密钥
     *
     * @param str
     * @return
     * @throws Exception
     */
    public Map<String, String> getMiYao(String str, String transAmt, Double c_fdMoney) throws Exception {
        Map<String, String> miYao = null;
        if (StringUtils.isEmpty(str)) {
            miYao = reflushMiYao(transAmt, c_fdMoney);
        } else {
            miYao = new HashMap<String, String>();
            //if(StringUtils.isEmpty(str)) return reflushMiYao(transAmt,c_fdMoney);
            String[] strA = str.split("_");
            if ("-1".equals(strA[0]) || StringUtils.isEmpty(strA[2].trim())) return reflushMiYao(transAmt, c_fdMoney);
            miYao.put("batchId", strA[2]);
            miYao.put("pinKey", strA[3]);
            miYao.put("macKey", strA[4]);
        }
        return miYao;
    }

    /**
     * 刷新瑞升银联socket 接口密钥
     * @return
     * @throws Exception
     */
    public Map<String, String> reflushMiYao(String transAmt, Double c_fdMoney) throws Exception {
        TchannelM tcm = getTchannelM(transAmt, c_fdMoney);
        RuiShengPayService aps = new RuiShengPayService(tcm.getMcode(), tcm.getTcode(), "000001", tcm.getMainKey(), null, null);

        Integer bankOrderNum = searchRuiShengTransId();
        String miyao = aps.login(bankOrderNum.toString());
        //保存密钥
        tchannelMDao.updateMobileTcOtherById(tcm.getId(), miyao);
        return getMiYao(miyao, transAmt, c_fdMoney);
    }


    /**
     * 查询瑞升银联订单号
     *
     * @return
     * @throws Exception
     */
    public Integer searchRuiShengTransId() throws Exception {
        return transOrderDao.searchRuiShengTransId();
    }

    /**
     * 余额查询
     * @param send
     * @return
     * @throws Exception
     */
    public BalanceResult balanceEnquiry(Qian4SendLog send) throws Exception {
        TchannelM tcm = tchannelMDao.searchTchannelMByCode(send.getCollectionType(), send.getMerchantId(), send.getTerminalId());
        Map<String, String> miyao = getMiYao(tcm.getOtherParam(), null, null);

        RuiShengPayService aps = new RuiShengPayService(send.getMerchantId(), send.getTerminalId(), miyao.get("batchId"), tcm.getMainKey(), miyao.get("pinKey"), miyao.get("macKey"));//getAnxinybPayService(send.getTransAmt());

        SendParam sendParam = new SendParam();
        BeanUtils.copyProperties(sendParam, send);
        return aps.balanceEnquiry(sendParam);
    }

    /**
     * 费率版收款
     *
     * @param send
     * @return
     * @throws Exception
     */
    public PurchaseResult billPayment(Qian4SendLog send, Tchannel tc) throws Exception {
        Double c_fdMoney = NumberUtil.roundF2((tc.getFdMaxFee() / tc.getFeeRate()));

        TchannelM tcm = tchannelMDao.searchTchannelMByCode(send.getCollectionType(), send.getMerchantId(), send.getTerminalId());
        Map<String, String> miyao = getMiYao(tcm.getOtherParam(), send.getTransAmt(), c_fdMoney);
        RuiShengPayService aps = new RuiShengPayService(send.getMerchantId(), send.getTerminalId(), miyao.get("batchId"), tcm.getMainKey(), miyao.get("pinKey"), miyao.get("macKey"));

        SendParam sendParam = new SendParam();

        BeanUtils.copyProperties(sendParam, send);
        PurchaseResult rs = aps.billPayment(sendParam);
        if ("00A0".equals(rs.getReqCode())) {
            miyao = reflushMiYao(send.getTransAmt(), c_fdMoney);
            rs = aps.billPayment(sendParam);
        }
        Integer status = null;
        Double addUseTotal = NumberUtil.roundF2(Integer.parseInt(send.getTransAmt())/100.00);
        if(!("0000".equals(rs.getReqCode()))) addUseTotal = 0.00;
        tchannelMDao.updateTchannelMUseMoney(tcm.getId(), addUseTotal, status);//交易金额累计
        return rs;
    }


    /**
     * 冲正
     *
     * @param send
     * @return
     * @throws Exception
     */
    public RevocationResult unBillPayment(Qian4SendLog send) throws Exception {
        Tchannel tc = tchannelDao.searchMobileTchannelByCode(send.getCollectionType());
        Double c_fdMoney = NumberUtil.roundF2((tc.getFdMaxFee() / tc.getFeeRate()));
        TchannelM tcm = tchannelMDao.searchTchannelMByCode(send.getCollectionType(), send.getMerchantId(), send.getTerminalId());
        Map<String, String> miyao = getMiYao(tcm.getOtherParam(), send.getTransAmt(), c_fdMoney);
        //冲正  重新创建接口对象
        RuiShengPayService aps = new RuiShengPayService(send.getMerchantId(), send.getTerminalId(), miyao.get("batchId"), tcm.getMainKey(), miyao.get("pinKey"), miyao.get("macKey"));

        SendParam sendParam = new SendParam();
        BeanUtils.copyProperties(sendParam, send);
        RevocationResult rr = aps.unBillPayment(sendParam);
//		if("00A0".equals(rr.getReqCode())){
//			miyao = reflushMiYao(send.getTransAmt(),c_fdMoney);
//			rr = aps.unBillPayment(send);
//		}
        return rr;
    }

    /**
     * 获得费率版支付接口
     *
     * @return
     * @throws Exception
     */
    public RuiShengPayService getRuiShengPayService(String transAmt, Double c_fdMoney) throws Exception {
        TchannelM tcm = getTchannelM(transAmt, c_fdMoney);
        if(tcm==null){
            return null;
        }
        Map<String, String> miyao = getMiYao(tcm.getOtherParam(), transAmt, c_fdMoney);
        //获取主密钥 和 终端号
        return new RuiShengPayService(tcm.getMcode(), tcm.getTcode(), miyao.get("batchId"), tcm.getMainKey(), miyao.get("pinKey"), miyao.get("macKey"));
    }

    private TchannelM getTchannelM(String transAmt, Double c_fdMoney) throws Exception {
        TchannelM tcm = null;
        Double money = 0.00;
        if (StringUtils.isNotEmpty(transAmt)) {
            money = Integer.parseInt(transAmt) / 100.0;
        }
        Long roleId = flRoleId;
        if (money > c_fdMoney) roleId = fdRoleId;
        double limits = Double.parseDouble(settingsService.getMainValueByFk("RUISHENG_TRADING_LIMIT"));
        List<TchannelM> list = tchannelMDao.searchMobileTCListByCodes(RuiSheng_TchannelId, roleId, limits);
        if(list.size()==0){
            return null;
        }
        tcm = list.get(0);
        //从配置文件读取限制金额
        if(limits != 0 && (money+tcm.getUseTotal()) > limits){
            tchannelMDao.updateTchannelMUseTime(tcm.getId());
            return null;
        }
        //更新使用时间
        tchannelMDao.updateTchannelMUseTime(tcm.getId());
        return tcm;
    }

    /**
     * 初始化 请求参数
     *
     * @param send
     * @param tc
     * @return
     * @throws Exception
     */
    public Qian4SendLog initSend(Qian4SendLog send, Tchannel tc) throws Exception {
        Double c_fdMoney = NumberUtil.roundF2((tc.getFdMaxFee() / tc.getFeeRate()));
        RuiShengPayService aps = getRuiShengPayService(send.getTransAmt(), c_fdMoney);
        if(aps==null){
            send.setBatchId(null);
            return send;
        }
        send.setBankOrderNum(searchRuiShengTransId().toString());//查询序列 获取动态流水号
        send.setBatchId(aps.batch);//批次号
        send.setMerchantId(aps.merchantId);
        send.setTerminalId(aps.terminalId);
        return send;
    }
}
